import 'dart:core';
import 'package:dk_flutter_base/dk_core.dart';
import 'package:flutter/material.dart';

/// 倒计时
/// [countdownUnit]:倒计时单位（时，分，秒）
/// [period]：计时器回调间隔，与countdownUnit搭配使用
/// [preString]：倒计时时间前面文案
/// [delayTime]：倒计时剩余时间（单位秒）
/// [onComplete]：倒计时到0时回调
class Countdown extends StatefulWidget {
  final CountdownUnit countdownUnit;
  final int period;
  final String preString;
  final int delayTime;
  final VoidCallback onComplete;

  Countdown(
      {this.countdownUnit = CountdownUnit.Seconds,
      this.period = 1,
      this.preString = "极速倒计时",
      this.delayTime = 60,
      this.onComplete});

  @override
  _CountdownState createState() => _CountdownState(delayTime);
}

class _CountdownState extends State<Countdown> {
  Timer _timer;
  int _seconds;

  _CountdownState(this._seconds);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      height: 24,
      child: Row(
        children: <Widget>[
          Container(
            width: 15,
            height: 15,
            child: Image(
                image: AssetImage(
                    "packages/flutter_dk_form/images/dk_form/time_icon.png")),
            margin: EdgeInsets.only(right: 7),
          ),
          Text(widget.preString +
              constructTime(_seconds).toString() +
              (widget.countdownUnit == CountdownUnit.Hours
                  ? "小时"
                  : (widget.countdownUnit == CountdownUnit.Minutes
                      ? "分钟"
                      : "秒")),style: TextStyle(color: Color(0xFFFF3252), fontSize: 12),),
        ],
      ),
      padding: EdgeInsets.only(left: 16),
    );
  }

  int constructTime(int seconds) {
    if (widget.countdownUnit == CountdownUnit.Hours) {
      return seconds ~/ 3600;
    } else if (widget.countdownUnit == CountdownUnit.Minutes) {
      return seconds ~/ 60;
    } else {
      return seconds;
    }
  }

  @override
  void initState() {
    super.initState();
    startTimer();
  }

  void startTimer() {
    Duration period = Duration(seconds: widget.period);
    if (widget.countdownUnit == CountdownUnit.Hours) {
      period = Duration(hours: widget.period);
    } else if (widget.countdownUnit == CountdownUnit.Minutes) {
      period = Duration(minutes: widget.period);
    } else if (widget.countdownUnit == CountdownUnit.Seconds) {
      period = Duration(seconds: widget.period);
    }

    _timer = Timer.periodic(period, (timer) {
      //更新界面
      setState(() {
        if (widget.countdownUnit == CountdownUnit.Hours) {
          _seconds = _seconds - 3600;
        } else if (widget.countdownUnit == CountdownUnit.Minutes) {
          _seconds = _seconds - 60;
        } else if (widget.countdownUnit == CountdownUnit.Seconds) {
          _seconds--;
        }
      });
      if (_seconds == 0) {
        //倒计时秒数为0，取消定时器
        cancelTimer();
        if (widget.onComplete != null) {
          widget.onComplete();
        }
      }
    });
  }

  void cancelTimer() {
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
    }
  }

  @override
  void dispose() {
    super.dispose();
    cancelTimer();
  }
}

enum CountdownUnit {
  ///时
  Hours,

  ///分
  Minutes,

  ///秒
  Seconds,
}
